window.addEventListener('load', () => {
    // 判断登录是否过期
    var nowTimestamp = Date.parse(new Date()) / 1000;
    var loginTimestamp = localStorage.getItem('timestamp') / 1000;
    var remFlag = null;
    remFlag = localStorage.getItem('remFlag') ? localStorage.getItem('remFlag') : 0;


    // 如果是记住密码后打开页面
    if (remFlag == 1) {
        // 判断登录时间小于七天
        if ((nowTimestamp - loginTimestamp) < 604800) {
            sessionStorage.setItem('flag', 1);
            axios.post('http://47.113.197.172:80/user/login', {
                name: localStorage.getItem('name'),
                password: localStorage.getItem('password')
            })
                .then(Response => {
                    // console.log(Response.data);
                    // 获取登录的用户身份和token令牌
                    var token = Response.data.token;
                    var id = Response.data.id;
                    sessionStorage.setItem('flag', 1);
                    sessionStorage.setItem('token', token);
                    sessionStorage.setItem('id', id);
                    sessionStorage.setItem('name', loginName);
                    sessionStorage.setItem('password', loginPassword);
                    addAvatar();

                })
                .catch(err => {
                    console.log(err);
                })

        } else {
            // 登录时间超过七天，清除本地缓存
            if (localStorage.getItem('timestamp')) {
                localStorage.removeItem('timestamp');
            }
            if (localStorage.getItem('name')) {
                localStorage.removeItem('name');
            }
            if (localStorage.getItem('password')) {
                localStorage.removeItem('password');
            }
            if (localStorage.getItem('remFlag')) {
                localStorage.removeItem('remFlag');
            }
            alert('登录超过七天，请重新登录');
        }
    }

    // 获取用户头像
    var avatar = document.getElementById('avatar');
    var addAvatar = function () {
        var id = sessionStorage.getItem('id');
        var baseUrl = 'http://47.113.197.172:80/user/info/';
        var finalUrl = baseUrl + id;
        axios.get(finalUrl)
            .then(Response => {
                avatar.src = Response.data.data.avatar;
            })
            .catch(err => {
                console.log(err);
            })
    }


    var url = 'http://47.113.197.172:80/articles';
    var num = 1;
    var token = sessionStorage.getItem('token');
    var flag = sessionStorage.getItem('flag');
    // 判断有没有登录，只有登录时flag才为1，没有登录或者退出登录flag都为0
    flag = flag ? flag : 0;
    // 判断有没有token，没有就传一个空的
    token = token ? token : '';

    // axios响应拦截器
    var getPassageAxios = axios.create();
    getPassageAxios.interceptors.response.use(function (res) {
        // 继续访问
        if (res.data.code == 1) {
            // console.log('请求成功');
            return res;
        }
    }, function (err) {
        console.log('请求失败');
        // 重新登录获取新的token
        axios.post('http://47.113.197.172:80/user/login', {
            name: sessionStorage.getItem('name'),
            password: sessionStorage.getItem('password')
        })
            .then(Response => {
                // 刷新token
                var newToken = Response.data.token;
                sessionStorage.setItem('token', newToken);
                location.reload();
            })
            .catch(err => {
                console.log(err);
            })
    })

    // 请求主页文章
    getPassageAxios({
        method: 'get',
        url: url,
        headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': token
        },
        params: {
            offset: 0,
            limit: 10
        }
    })
        .then(Response => {
            addInformation(Response);
        })
        .catch(err => {
            // alert('请点击确认重新获取页面信息');
        })




    var timer = null;
    // 给页面滚动条添加滚动监听事件
    window.addEventListener('scroll', function () {
        clearTimeout(timer);
        // 
        var scrollTop = document.documentElement.scrollTop;
        var scrollHeight = document.documentElement.scrollHeight;
        var clientHeight = document.documentElement.clientHeight;
        // 当滚动条移动至80%以上时，再请求20篇文章
        if (scrollTop / (scrollHeight - clientHeight) >= 0.8) {
            // 防抖优化，避免一次发出过多请求
            timer = setTimeout(function () {
                axios({
                    method: 'get',
                    url: url,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': token
                    },
                    params: {
                        offset: 10 * num,
                        limit: 10
                    }
                })
                    .then(Response => {
                        addInformation(Response);
                    })

                    .catch(err => {
                        console.log(err);
                    })
                num++;
                // console.log(num);
            }, 200)

        }


        var rightSection = document.querySelector('.rightSection');
        var writerList = rightSection.querySelector('.writerList');
        var mainFooter = rightSection.querySelector('.mainFooter');

        if (scrollTop > 1800) {
            console.log(1);
            rightSection.style.position = 'fixed';
            rightSection.style.top = 18 + 'px';
            rightSection.style.marginLeft = 720 + 'px';
            writerList.style.display = 'none';
            mainFooter.style.display = 'none';
        } else {
            rightSection.style.position = 'relative';
            rightSection.style.top = 0;
            rightSection.style.marginLeft = 0;
            writerList.style.display = 'block';
            mainFooter.style.display = 'block';
        }

    })

    // 根据不同标签显示文章列表
    var section = document.querySelector('.section');
    var categoryLi = section.querySelectorAll('li');
    for (i = 0; i < 10; i++) {
        categoryLi[i].addEventListener('click', function () {
            var category = this.innerHTML;
            // 排他算法，让点击的那个标签变色
            for (i = 0; i < 10; i++) {
                categoryLi[i].style.color = 'rgb(113, 119, 124)';
            }
            this.style.color = 'rgb(0, 127, 255)';
            if (category == '综合') {
                axios({
                    method: 'get',
                    url: url,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': token
                    },
                    params: {
                        offset: 0,
                        limit: 10
                    }
                })
                    .then(Response => {
                        removePassageLi();
                        addInformation(Response);
                    })

                    .catch(err => {
                        console.log(err);
                    })
            } else {
                axios({
                    method: 'get',
                    url: url,
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': token
                    },
                    params: {
                        category: category,
                        offset: 0,
                        limit: 10
                    }
                })
                    .then(Response => {
                        removePassageLi();
                        addInformation(Response);
                    })

                    .catch(err => {
                        console.log(err);
                    })
            }

        })
    }

    // 移除主页已有的文章信息
    function removePassageLi() {
        var formerPassageLi = indexPassageList.querySelectorAll('.indexPassageListLi');
        for (i = 0; i < formerPassageLi.length - 1; i++) {
            indexPassageList.removeChild(formerPassageLi[i]);
        }
    }

    // 将获取到的信息填入页面
    var indexPassageList = document.querySelector('#indexPassageList');
    var indexPassageListLi = document.querySelector('.indexPassageListLi');
    function addInformation(Response) {
        for (i = 0; i < 10; i++) {
            // 复制一个节点
            var appendNewLi = indexPassageListLi.cloneNode(true);
            // 修改节点里面的内容
            var writerName = appendNewLi.querySelector('.writerName');
            writerName.innerHTML = Response.data.data.articlesList[i].userInfo.name;
            var category = appendNewLi.querySelector('.category');
            category.innerHTML = Response.data.data.articlesList[i].category;
            var passageTitle = appendNewLi.querySelector('.passageTitle');
            passageTitle.innerHTML = Response.data.data.articlesList[i].title;
            var passageBrief = appendNewLi.querySelector('.passageBrief');
            passageBrief.innerHTML = Response.data.data.articlesList[i].brief;
            var likeCount = appendNewLi.querySelector('.likeCount');
            likeCount.innerHTML = Response.data.data.articlesList[i].likeCount;
            var commentCount = appendNewLi.querySelector('.commentCount');
            commentCount.innerHTML = Response.data.data.articlesList[i].commentCount;
            var watchCount = appendNewLi.querySelector('.watchCount');
            watchCount.innerHTML = Math.round(Math.random() * 1000);

            // 根据是否点赞显示不同的图片
            var likeImg = appendNewLi.querySelector('#likeImg');
            var isLike = Response.data.data.articlesList[i].isLike;
            if (isLike === 1) {
                likeImg.src = '../img/icon-like-already.png';
            }
            else {
                likeImg.src = '../img/icon-like.png';
            }

            // 判断有无封面，有显示，没有就不显示
            var passageCover = appendNewLi.querySelector('.passageCover');
            var passageCoverImg = passageCover.querySelector('img');
            if (Response.data.data.articlesList[i].coverUrl == null) {
                passageCover.style.display = 'none';
            } else {
                passageCoverImg.src = Response.data.data.articlesList[i].coverUrl;
            }

            // 获取文章id和作者id
            appendNewLi.id = Response.data.data.articlesList[i].id;
            var writerId = Response.data.data.articlesList[i].userInfo.id;
            var likeBtn = appendNewLi.querySelector('.likeBtn');
            // 分别获取三个自定义属性（文章id，作者id，是否已经点赞），用于点击事件
            likeBtn.id = appendNewLi.id;
            likeBtn.writerId = writerId;
            likeBtn.isLike = isLike;

            // 将这个节点插入到ul中
            indexPassageList.appendChild(appendNewLi);

            appendNewLi.addEventListener('click', function () {
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id;
                // 成功获取请求的文章接口
                // console.log(finalUrl);
                // 将需要调用的接口存到本地，在打开文章详情页可以跨页面调用
                sessionStorage.setItem('finalUrl', finalUrl);
                // 跳转到文章详情页
                window.open("../html/passage.html");
            })
        }

        // 点赞功能
        var likeBtnList = document.querySelectorAll('.likeBtn');
        for (i = 1; i < likeBtnList.length; i++) {
            likeBtnList[i].setAttribute('flag', 0);

            likeBtnList[i].onclick = function (event) {
                event.stopPropagation();
                // 没有登录的状态下不能点赞
                if (flag == 0) {
                    alert('请先登录');
                }
                else {
                    if (this.isLike == 1) {
                        if (this.flag == 1) {
                            this.children[0].src = '../img/icon-like-already.png';
                            this.children[1].innerHTML++;
                            this.flag = 0;
                        } else {
                            this.children[0].src = '../img/icon-like.png';
                            this.children[1].innerHTML--;
                            this.flag = 1;
                        }
                    }
                    if (this.isLike == 0) {
                        if (this.flag == 0) {
                            this.children[0].src = '../img/icon-like.png';
                            this.children[1].innerHTML--;
                            this.flag = 1;
                        } else {
                            this.children[0].src = '../img/icon-like-already.png';
                            this.children[1].innerHTML++;
                            this.flag = 0;
                        }
                    }

                }

                // 数据交互
                var baseUrl = 'http://47.113.197.172:80/articles/';
                var id = this.id;
                var finalUrl = baseUrl + id + '/likes';
                var data = JSON.stringify({
                    likedId: this.writerId
                })
                axios({
                    method: 'post',
                    url: finalUrl,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token
                    },
                    data: data
                })
                    .then(Response => {
                        console.log(Response.data);
                    })
                    .catch(err => {
                        console.log('点赞失败');
                    })

            }
        }

    }


    // 关闭页面广告
    var adv1 = document.querySelector('.adv1');
    var closeBtn1 = adv1.querySelector('div');
    var adv2 = document.querySelector('.adv2');
    var closeBtn2 = adv2.querySelector('div');
    closeBtn1.onclick = function () {
        adv1.style.display = 'none';
    }
    closeBtn2.onclick = function () {
        adv2.style.display = 'none';
    }

    // 返回顶部
    var toTop = document.querySelector('.toTop');
    toTop.onclick = function () {
        var s = document.documentElement.scrollTop;
        topTimer = window.setInterval(function () {
            s -= 50;
            if (s < 0) {
                clearInterval(topTimer);
            }
            // window.scrollTo(x, y)
            // 滚动到文档中的某个坐标
            window.scrollTo(0, s);
        }, 6);
    }

    // 笔记模块
    var leftWing = document.querySelector('.leftWing');
    var notesClose = document.querySelector('.notesClose');
    var notes = document.querySelector('.notes');
    var leftFlag = 0;
    leftWing.onclick = function () {
        if (leftFlag == 0) {
            notes.style.display = 'block';
            leftFlag = 1;
        } else {
            notes.style.display = 'none';
            leftFlag = 0;
        }
    }
    notesClose.onclick = function () {
        notes.style.display = 'none';
        leftFlag = 0;
    }

    // 建议
    var rightWing = document.querySelector('.rightWing');
    var adviceClose = document.querySelector('.adviceClose');
    var advice = document.querySelector('.advice');
    var rightFlag = 0;
    rightWing.onclick = function () {
        if (rightFlag == 0) {
            advice.style.display = 'block';
            rightFlag = 1;
        } else {
            advice.style.display = 'none';
            rightFlag = 0;
        }
    }
    adviceClose.onclick = function () {
        advice.style.display = 'none';
        rightFlag = 0;
    }




})